// 实现这个项目的构建任务
/**
 * 1.安装依赖 gulp 以及需要用到的插件
 * 2.编译资源:模板，sass，js，压缩资源，html,css,js,图片字体文件等
 * 3.整理构建思路，区分生产和开发环境区别
 *  3.1 开发环境
 *      1.替换路由  browser-sync
 *      2.热加载: gulp 监听源码变化进行编译，browser-sync监听dev目录
 *  3.2 生产环境
 */

const { src, dest, series, parallel, watch } = require("gulp");

const yargs = require("yargs").argv;
const cmd = yargs._[0];
const dir = cmd === "dev" ? "dev" : "dist";
// 删除文件
const del = require("del");

//自动加载插件
const plugins = require("gulp-load-plugins")();

// 本地服务
const browserSync = require("browser-sync").create();

const serve = () => {
  watcher();
  browserSync.init({
    notify: false,
    server: {
      baseDir: ["dist", "src", "pubilc"],
      routes: {
        "/node_modules": "node_modules", //替换路由
      },
    },
    open: false,
    files: "dist",
  });
};

const watcher = () => {
  watch("src/**/*.scss", style);
  watch("src/**/*.js", script);
  watch("src/*.html", html);
};

// 删除
const clean = () => {
  return del([dir]);
};
// scss
const style = () => {
  return src("src/assets/styles/*.scss", { base: "src" })
    .pipe(plugins.sass())
    .pipe(dest(dir));
};
// html
const html = () => {
  return src("src/*.html")
    .pipe(plugins.swig({ defaults: { cache: false } }))
    .pipe(dest(dir));
};
// js
const script = () => {
  return src("src/assets/scripts/*.js", { base: "src" })
    .pipe(plugins.babel({ presets: ["@babel/preset-env"] }))
    .pipe(dest(dir));
};
// image
const image = () => {
  return src("src/assets/images/**", { base: "src" })
    .pipe(plugins.imagemin())
    .pipe(dest(dir));
};
// fonts
const fonts = () => {
  return src("src/assets/fonts/**", { base: "src" })
    .pipe(plugins.imagemin())
    .pipe(dest(dir));
};
const pub = () => {
  return src("public/**").pipe(dest(dir));
};
// useref
const useref = () => {
  return src("dist/*.html")
    .pipe(plugins.useref({ searchPath: ["dist", "."] }))
    .pipe(dest(dir));
};
// 压缩
const uglify = () => {
  return src("dist/**/*.js", { base: "dist" })
    .pipe(plugins.uglify())
    .pipe(dest("dist"));
};
const minCss = () => {
  return src("dist/**/*.css", { base: "dist" })
    .pipe(plugins.minifyCss())
    .pipe(dest("dist"));
};
const htmlMin = () => {
  return src("dist/**/*.html", { base: "dist" })
    .pipe(
      plugins.htmlmin({
        collapseWhitespace: true,
        minifyCSS: true,
        minifyJS: true,
      })
    )
    .pipe(dest("dist"));
};

const complite = parallel(style, html, script);
const extre = parallel(fonts, pub);
const min = parallel(uglify, minCss, htmlMin);
const build = series(clean, parallel(complite, extre), useref, min); // 其他环境
const dev = series(clean, complite, serve); // 开发

module.exports = {
  build,
  dev,
  clean,
};
